package admin

import (
	"grpc.getaway.adminspro.padmins.com/internal/api/module/admin/container"
	"grpc.getaway.adminspro.padmins.com/internal/api/utils/rpc"
	pbAdmin "grpc.getaway.adminspro.padmins.com/pkg/proto/admin"
	"reflect"
	"strconv"
	"strings"
)

func Add(c *container.Context) (interface{}, error) {

	status, _ := strconv.ParseInt(c.Request.ParamsToString("status", "1"), 10, 32)
	req := &pbAdmin.AdminAddReq{
		OperaterId: c.Auth.Data.Admin.Id,
		Admin: &pbAdmin.Admin{
			Email:    c.Request.ParamsToString("email"),
			Username: c.Request.ParamsToString("username"),
			Nickname: c.Request.ParamsToString("nickname"),
			Password: c.Request.ParamsToString("password"),
			Avatar:   c.Request.ParamsToString("avatar"),
			Status:   int32(status),
		},
		RoleId: []int64{},
	}

	if reflect.TypeOf(c.Request.Params("role_id")).Kind() == reflect.Slice {
		role_id := c.Request.Params("role_id").([]string)
		req.RoleId = make([]int64, len(role_id))
		for i, roleId := range role_id {
			if rid, e := strconv.ParseInt(roleId, 10, 64); e == nil {
				req.RoleId[i] = rid
			}
		}
	} else {
		role_id := strings.Split(c.Request.ParamsToString("role_id", ""), ",")
		req.RoleId = make([]int64, len(role_id))
		for i, roleId := range role_id {
			if rid, e := strconv.ParseInt(roleId, 10, 64); e == nil {
				req.RoleId[i] = rid
			}
		}
	}

	resp, e := rpc.GetAdminClient().AdminAdd(c.GetContext(), req)

	if e != nil {
		return resp, e
	}

	return map[string]map[string]interface{}{
		"row": {"id": resp.Id},
	}, nil

}
